package com.zecan.blog.security.service.impl;

import com.zecan.blog.common.status.UserStatus;
import com.zecan.blog.controller.exception.UserException;
import com.zecan.blog.dao.ArticleMapper;
import com.zecan.blog.dao.UserMapper;
import com.zecan.blog.security.entity.AccountUser;
import com.zecan.blog.entity.BlogUser;
import com.zecan.blog.service.BlogUserService;
import com.zecan.blog.utils.BlogConstant;
import com.zecan.blog.utils.SpringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName UserDetailServiceImpl
 * @Description
 * @date 2022/10/29 18:28
 * @Version 1.0
 * 实现UserDetailsService 中的 从数据库获取用户名 完成用户输入的用户名的信息校验
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

     UserMapper userMapper = SpringUtils.getBean(UserMapper.class);

     ArticleMapper articleMapper = SpringUtils.getBean(ArticleMapper.class);
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 根据用户名获取用户信息
        BlogUser blogUser = userMapper.findUserByUsername(username);
        if(blogUser == null) {
            throw new UserException(UserStatus.USER_NOT_FOUND);
        }
        // 这里 存入当前用户的文章数量
        Integer userArticleCount = articleMapper.findUserArticleCount(blogUser.getUserId());
        // 返回用户信息, 与用户输入的账号密码进行对比 错误 则进认证失败处理器
        return new AccountUser(blogUser.getUserId(),blogUser.getUsername(),
                blogUser.getPassword(),getAuthentication(blogUser.getUserId()),
                blogUser.getUserAvatarUrl(), blogUser.getUserNickname(), blogUser.getUserEmail(),userArticleCount);
    }


    /**
     * 根据用户信息获取用户权限
     * @param userId
     * @return
     */
    private  List<GrantedAuthority> getAuthentication(Long userId) {
        List<GrantedAuthority> authorityList= null;
        // 保存权限信息
        switch (userMapper.findUserAuthenticationInfoById(userId)) {
            case 0 :
                authorityList =  AuthorityUtils.createAuthorityList(BlogConstant.BLOG_NORMAL_USER);
                break;
            case 1:
                authorityList =   AuthorityUtils.createAuthorityList(BlogConstant.BLOG_ADMIN);
                break;
        }

        return  authorityList;
    }


}
